﻿/// <reference path="jquery-1.5.1-vsdoc.js" />
//CMAT Common
var _MAX_COMMENTS_LENGTH_ = 512;
//Ban or Unban.
var _URL_IsPaymentInstrumentBanned_ = "PaymentInstrument/IsPaymentInstrumentBanned";
var _URL_BanPaymentInstrument_ = "PaymentInstrument/BanOrUnBanPaymentInstrument";
var _URL_BanOrUnbanTemplate_ = "PaymentInstrument/BanOrUnBanPaymentInstrumentTemplate";
var _URL_BanOrUnbanGetCountrys_ = "PaymentInstrument/GetCountrys";

//defined local info config
var LocalInfo = "";
//defined keycode
var KeyUP = 38;
var KeyDown = 40;
var Enter = 13;
var Tab = 9;
var Esc = 27;

var tabback = 9999; //disabled

var _Err_Type_Text_ = "text";
var _Err_Type_Alert_ = "alert";
var _Err_Type_TGrid_ = "tgrid";
var _Err_Type_Panel_ = "panel";
var _Err_Type_PanelPart_ = "panelPart";
var _Err_Type_Dialog_ = "dialog";

var _ZipCodeXML;

// Control Type
var _Ctl_CType_Button_ = "button";
var _Ctl_CType_CheckBox_ = "checkbox";

//it's used to store current selected button id when loading panel displaying.
var _Current_ID_ = "";

function _LOCAL_ShowExceptionError(exceptionId, msg) {
    if (exceptionId && msg) {
        $("[exception_error='" + exceptionId + "']").removeClass('hide').text(msg);
    }
}
function _LOCAL_HideExceptionError(exceptionId) {
    if (exceptionId) {
        $("[exception_error='" + exceptionId + "']").addClass('hide').text("");
    }
}

$.extend({
    GetErrorMessageFromJsonResult: function (e) {
        var exception = {};
        exception = $.parseJSON(e.responseText);
        if (exception.ErrorType == "CTP") {
            return GetLocalFieldByID("error_error") + exception.CTPErrorMessage;
        }
        else {
            return GetLocalFieldByID("error_error") + exception.ErrorMessage;
        }
    }
});

$.fn.ShowError = function (options) {
    var $selectEle = $(this);

    $.fn.ShowError.defaults = {
        exceptionId: "",
        ex: { ErrorType: "common", ErrorMessage: GetLocalFieldByID("error_server") },
        showType: "alert", // text | alert | tgrid | panel      
        textType: function () {
            if (this.ex) {
                if (this.exceptionId != "") {
                    //I think .we can remove this code.
                    $selectEle = $("[exception_error='" + this.exceptionId + "']");
                    new HandleError(this.ex).message(function (msg) {
                        $selectEle.removeClass('hide').text(GetLocalFieldByID("error_error") + getErrorMsg(msg));
                    }).handle();
                } else {
                    //exception = $.parseJSON(this.ex.responseText);
                    new HandleError(this.ex).message(function (msg) {
                        $selectEle.removeClass('hide').addClass("txtError").text(GetLocalFieldByID("error_error") + getErrorMsg(msg));
                    }).handle();
                }
            }
        },
        alertType: function () {
            if (this.ex.responseText) {
                exception = $.parseJSON(this.ex.responseText);
                if (exception.ErrorType == "CTP") {
                    alert(GetLocalFieldByID("error_error") + exception.ErrorMessage);
                }
                else {
                    new HandleError(this.ex).message(function (msg) {
                        alert(GetLocalFieldByID("error_error") + getErrorMsg(msg));
                    }).handle();
                }
            }
            else {
                alert("UnknowError:");
            }
        },
        panelType: function () {
            if (this.ex.responseText) {
                new HandleError(this.ex).message(function (msg) {
                    $selectEle.html("<div class='warning_row'><span>" + GetLocalFieldByID("error_error") + getErrorMsg(msg) + "</span></div>");
                }).handle();
            }
            else {
                alert("UnknowError:");
            }
        },
        panelPartType: function () {
            if (this.ex.responseText) {
                $selectEle.html(this.ex.responseText);
            } else if (this.ex.XMLHttpRequest != undefined) {
                $selectEle.html(this.ex.XMLHttpRequest.responseText);
                this.ex.XMLHttpRequest.status = 0;
            }
            else {
                alert("UnknowError:");
            }
        },
        tgridType: function () {
            if (this.ex && this.ex.XMLHttpRequest && this.ex.target) {
                var $gridTarget;
                if (this.ex.XMLHttpRequest == undefined || this.ex.XMLHttpRequest == null) {
                    exception = getErrorMsg(this.ex);
                    $gridTarget = $selectEle;
                } else {
                    exception = $.parseJSON(this.ex.XMLHttpRequest.responseText);
                    $gridTarget = $(this.ex.target);
                }


                var colspan = $gridTarget.find(".t-grid-content table col").length;



                if ($gridTarget.find("tr.t-no-data td").length > 0) {
                    $gridTarget.find("tr.t-no-data td").html("<div class='warning_row'><span>" + GetLocalFieldByID("error_error") + exception.message + "</span></div>");
                } else {
                    $gridTarget.find(".t-grid-content tbody").html("<tr class=\"t-no-data\"><td colSpan=\"" + colspan + "\"><div class=\"warning_row\"><span>" + GetLocalFieldByID("error_error") + exception.message + "</span></div></td></tr>");
                }
                this.ex.XMLHttpRequest.status = 0;
            } else if (this.ex.XMLHttpRequest == undefined || this.ex.XMLHttpRequest == null) {
                exception = this.ex;
                $gridTarget = $selectEle;
                var colspan = $gridTarget.find(".t-grid-content table col").length;
                var grid = $gridTarget.data('tGrid');
                if (grid != null || grid != undefined) {
                    grid.total = 0;
                    grid.dataBind(Array());
                    if ($gridTarget.find("tr.t-no-data td").length > 0) {
                        new HandleError(exception).message(function (msg) {
                            $gridTarget.find("tr.t-no-data td").html("<div class='warning_row'><span>" + GetLocalFieldByID("error_error") + getErrorMsg(msg) + "</span></div>");
                        }).handle();
                    }
                }
            }
            else {
                this.ex.XMLHttpRequest.status = 0;
                alert("unknow error");
            }
        },
        dialogType: function () {

            if (this.ex) {
                //exception = $.parseJSON(this.ex.responseText);
                new HandleError(this.ex).message(function (msg) {
                    $selectEle.html("<div class='warning_row'><span>" + GetLocalFieldByID("error_error") + getErrorMsg(msg) + "</span></div>");
                }).handle();
            }
        },
        OnShow: function () {
            switch (this.showType) {
                case _Err_Type_Text_: { this.textType(); break; }
                case _Err_Type_Alert_: { this.alertType(); break; }
                case _Err_Type_TGrid_: { this.tgridType(); break; }
                case _Err_Type_Panel_: { this.panelType(); break; }
                case _Err_Type_PanelPart_: { this.panelPartType(); break; }
                case _Err_Type_Dialog_: { this.dialogType(); break; }
            }
        }
    };

    var opts = $.extend({}, $.fn.ShowError.defaults, options);
    opts.OnShow();
}

function GetXMLFileByAjax(fileName, defaultFileName, callback) {
    var params = {};
    params["fileName"] = fileName;
    params["defaultFileName"] = defaultFileName;
    $.ajax({
        url: WebRoot + "Account/GetLanguageXML", // localInfoSrc,
        data: params,
        cache: true,
        async: false,
        success: function (xml) {
            xml = $.parseXML(xml);
            if (xml != undefined && callback != "") {
                callback(xml);
            }
            else {
                alert(e.responseText);
            }
        },
        //Cannot find the xml by lang, use the default en-us
        error: function (e) {
            alert(e.responseText);
        }
    });
}
$.fn.CustomCheckBox = function (options) {
    $.fn.CustomCheckBox.defaults = {
        action: "html", //append,html,prepend,after,before
        checked: true,
        text: "",
        value: "",
        onClick: "",
        id: "",
        cssClass: "",
        tableIndex: "",
        disabled: false
    };
    var opts = $.extend({}, $.fn.CustomCheckBox.defaults, options);
    var htmlString = new Array("");
    htmlString.push("<span class='plusChk ");
    if (opts.checked) {
        htmlString.push("checked ");
    }
    if (opts.cssClass != "") {
        htmlString.push(opts.cssClass);
    }
    htmlString.push("'")
    if (opts.disabled) {
        htmlString.push(" disabled='disabled' ");
    }
    if (opts.value != "") {
        htmlString.push(" value='" + opts.value + "' ");
    }
    if (opts.id != "") {
        htmlString.push(" id='" + opts.id + "' ");
    }
    if (opts.tableIndex != "") {
        htmlString.push(" tableIndex='" + opts.tableIndex + "' ");
    }
    if (opts.text != "") {
        htmlString.push("><span class='plusChkText'>" + opts.text + "</span></span>");
    }
    var $checkBox;
    switch (opts.action) {
        case "html": { $(this).find("*").remove(); $checkBox = $(this).append(htmlString.join("")); break; }
        case "append": { $checkBox = $(this).append(htmlString.join("")); break; }
        case "after": { $checkBox = $(this).after(htmlString.join("")); break; }
        case "before": { $checkBox = $(this).before(htmlString.join("")); break; }
        case "prepend": { $checkBox = $(this).prepend(htmlString.join("")); break; }
    }
    if (opts.onClick != "") {
        $checkBox.click(function () {
            opts.onClick($checkBox);
        });
    }
    return $checkBox;
}

//Custom Input with validate
$.fn.CustomTextBox = function (options) {
    $.fn.CustomTextBox.defaults = {
        action: "html", //append, html, prepend ,after, before
        cssClass: "",
        readonly: false,
        width: "100%",
        id: "",
        tabIndex: "",
        validateType: "string",
        defaultErrorMessage: "",
        requireErrorMessage: "",
        typeErrorMessage: "",
        lengthErrorMessage: "",
        errorControl: true,
        maxLength: "512",
        minLength: "0",
        requiredField: -1,
        head: "",
        defaultValue: "",
        showAsterisk: false,
        disableCopy: false
    };
    //Create custom textbox
    var opts = $.extend({}, $.fn.CustomTextBox.defaults, options);
    if (opts.showAsterisk && opts.requiredField > -1) {
        opts.defaultValue += " *";
        opts.head += " *";
    }
    var htmlString = new Array("");
    htmlString.push("<div class='input_text' style='width:" + opts.width + ";'><div><input ctrkind='textbox' type='text' ");
    if (opts.id != "") {
        htmlString.push("id='" + opts.id + "' ");
    }
    if (opts.tabIndex != "") {
        htmlString.push("tabIndex='" + opts.tabIndex + "' ");
    }
    if (opts.validateType != "") {
        htmlString.push("validatetype='" + opts.validateType + "' ");
    }
    if (opts.minLength != "") {
        htmlString.push("minLength='" + opts.minLength + "' ");
    }
    if (opts.maxLength != "") {
        htmlString.push("maxlength='" + opts.maxLength + "' ");
    }
    htmlString.push("requiredField='" + opts.requiredField + "' ");
    if (opts.defaultValue != "") {
        htmlString.push("value='" + opts.defaultValue + "' ");
    }
    if (opts.cssClass != "") {
        htmlString.push("class='" + opts.cssClass + "' ");
    }
    htmlString.push("width='" + opts.width + "' ");
    htmlString.push("head='" + opts.head + "' ");
    if (opts.readonly) {
        htmlString.push("readonly='" + opts.readonly + "' ");
    }
    if (opts.disableCopy) {
        htmlString.push("oncopy='javascript:return false;' ");
        htmlString.push("oncut='javascript:return false;' ");
    }

    htmlString.push("/></div></div>");
    if (opts.errorControl) {
        htmlString.push("<div class='txtError hide' validate_error='" + opts.id + "'");
        if (opts.defaultErrorMessage != "") {
            htmlString.push(" default_error_message='" + opts.defaultErrorMessage + "'");
        }
        if (opts.requireErrorMessage != "") {
            htmlString.push(" require_error_message='" + opts.requireErrorMessage + "'");
        }
        if (opts.lengthErrorMessage != "") {
            htmlString.push(" length_error_message='" + opts.lengthErrorMessage + "'");
        }
        if (opts.typeErrorMessage != "") {
            htmlString.push(" type_error_message='" + opts.typeErrorMessage + "'");
        }
        htmlString.push("></div>");
    }
    //Choose html add method: append/html/prepend
    switch (opts.action) {
        case "append": { $(this).append(htmlString.join("")); break; }
        case "html": { $(this).find("*").remove(); $(this).append(htmlString.join("")); break; }
        case "after": { $(this).after(htmlString.join("")); break; }
        case "before": { $(this).before(htmlString.join("")); break; }
        case "prepend": { $(this).prepend(htmlString.join("")); break; }
    }
}
//-----------process phone number
function ProcessPhoneNumber(value) {
    if (value) {
        value = value.replace(/[-.\s]/ig, "");
    }
    return value;
}
//Submit Validtae
$.fn.submitValidate = function () {
    $("input[validatetype='phonenumber']").each(function () {
        if (!$(this).hasClass("textTip")) {
            $(this).attr("value", ProcessPhoneNumber($(this).attr("value")));
        }
    });
    $(this).find("input").each(function () {
        if ($(this).closest("[class~='hide']").length == 0) {
            var $validate_error = $("[validate_error='" + $(this).attr("id") + "']");
            $(this).removeClass("inputerror");
            $validate_error.addClass("hide");
            if ($(this).is("[validatetype]")) {
                $(this).focusout();
            }
            if ($(this).is("[requiredField]")) {
                if ($(this).attr("requiredField") > -1) {
                    if ($(this).closest(".custom_dropdownlist").length > 0 ? !$(this).attr("val") : ($(this).hasClass("textTip") || !$(this).attr("value"))) {
                        $(this).addClass("inputerror");
                        //show the custom message 
                        if ($validate_error.attr("require_error_message")) {
                            $validate_error.removeClass("hide").text($validate_error.attr("require_error_message"));
                        }
                        //show the default message 
                        else {
                            if ($validate_error.attr("default_error_message")) {
                                $validate_error.removeClass("hide").text($validate_error.attr("default_error_message"));
                            }
                            else {
                                $validate_error.removeClass("hide").text(GetLocalFieldByID("error_input_notnull"));
                            }
                        }
                    }

                    else {
                        if ($(this).attr("requiredField") > $(this).attr("value").length) {
                            $(this).addClass("inputerror");
                            if ($validate_error.attr("length_error_message")) {
                                $validate_error.addClass("txtError").removeClass("hide").text($validate_error.attr("length_error_message"));
                            }
                            else {
                                if ($validate_error.attr("default_error_message")) {
                                    $validate_error.removeClass("hide").text($validate_error.attr("default_error_message"));
                                }
                                else {
                                    $validate_error.removeClass("hide").text(GetLocalFieldByID("error_input_lessLength") + $(this).attr("requiredField"));
                                }
                            }
                        }
                    }
                }
            }
            if ($(this).is("[minLength]")) {
                if (!$(this).hasClass("textTip") && $(this).attr("value") != "") {
                    if ($(this).attr("minLength") > $(this).attr("value").length) {
                        $(this).addClass("inputerror");
                        if ($validate_error.attr("length_error_message")) {
                            $validate_error.removeClass("hide").text($validate_error.attr("length_error_message"));
                        }
                        else {
                            $validate_error.removeClass("hide").text(GetLocalFieldByID("error_input_lessLength") + $(this).attr("minLength"));
                        }
                    }
                }
            }
        }
    });
    if ($(this).find("input[class~='inputerror']").length > 0) {
        return false;
    }
    else {
        return true;
    }
}

//Clear the plan
$.fn.clearHtmlControls = function () {
    $(this).find("textarea").each(function () {
        $(this).attr("value", "");
    });
    $(this).find("input").each(function () {
        if ($(this).closest(".input_text").length == 1 || $(this).closest(".custom_input").length == 1) {
            if ($(this).is("[head]")) {
                $(this).removeClass("inputerror").addClass("textTip").attr("value", $(this).attr("head"));
            }
            else {
                $(this).attr("value", "");
            }
        }
        else if ($(this).closest(".custom_dropdownlist").length == 1) {
            $(this).removeClass("inputerror");
            if (!$(this).closest(".custom_dropdownlist").is("[type='node']")) {
                if ($(this).attr("defaultText")) {
                    $(this).attr("value", $(this).attr("defaultText"));
                }
                else {
                    $(this).attr("value", "");
                }
                if ($(this).attr("defaultvalue")) {
                    $(this).attr("val", $(this).attr("defaultvalue"));
                }
                else {
                    $(this).attr("val", "");
                }
            }
        }
    });
    $(this).find("[validate_error]").addClass("hide").text("");
}

var DropDownListClickEvents = {};
var DropDownListMouseoverEvents = {};
var DropDownListMouseleaveEvents = {};
var DropDownListKeyUpEvents = {};
var DropDownListKeyPressEvents = {};
var DropDownListKeyDownEvents = {};
//Custom Dropdown List
$.fn.CustomDropDownList = function (options) {
    var $dropDownlists;
    $.fn.CustomDropDownList.defaults = {
        action: "html", //append, html, prepend ,after, before,replaceWith,""
        data: "",
        cssClass: "",
        defaultText: "",
        defaultValue: "",
        head: "",
        disable: false,
        width: "100%",
        requiredField: -1,
        defaultErrorMessage: "",
        requireErrorMessage: "",
        requiredmessageid: "",
        errorControl: false,
        readOnly: true,
        id: "",
        tabIndex: "",
        height: "",
        type: "",
        onBeforeLoad: "",
        onLoad: "",
        onTextChange: "",
        onClick: "",
        onClickItem: "",
        onMouseover: "",
        onMouseoverItem: "",
        onMouseleave: "",
        onMouseleaveItem: "",
        onKeyDown: "",
        onKeyDownItem: "",
        onKeyPress: "",
        onKeyPressItem: "",
        onKeyUp: "",
        onKeyUpItem: "",
        emptyText: "",
        autoComplete: true,
        isListOverflow: true,
        refactorVersion: false
    };

    var opts = $.extend({}, $.fn.CustomDropDownList.defaults, options);

    /*initial the dropdownlist*/
    $(this).each(function () {
        /*before loading*/
        if (opts.onBeforeLoad != "") {
            opts.onBeforeLoad();
        }
        if (opts.data != "") {
            //Set the first item as default item When the defaultText is empty
            if (opts.defaultText == "") {
                //This variable is service for loop.but I had been comments.
                // var i = 0
                // Change the logic.The max computation of O(n).
                if (opts.data) {
                    for (var key in opts.data) {
                        opts.defaultText = opts.data[key];
                        opts.defaultValue = key;
                        break;
                    }
                    // This loop lose the increment(i++);
                    // Unfortunately, this problem not effect the function(Main project).
                    //                    $.each(opts.data, function (key, value) {
                    //                        if (i == 0) {
                    //                            opts.defaultText = value;
                    //                            opts.defaultValue = key;
                    //                        }
                    //                    });
                }
            }
            //Create drop down list html;
            var htmlString = new Array("");
            htmlString.push("<div class='custom_dropdownlist' style='z-index:0; width:" + opts.width + ";'");
            if (opts.refactorVersion) {
                htmlString.push(" refactorVersion='" + opts.refactorVersion + "'");
            }
            if (opts.type != "") {
                htmlString.push(" type='" + opts.type + "'");
            }
            htmlString.push(" ><div class='l_custom_dropdownlist'><div class='r_custom_dropdownlist'>");
            htmlString.push("<input ctrkind='ddlist' id='" + opts.id + "'");
            if (opts.readOnly) {
                htmlString.push(" readonly='readonly'");
            }
            if (opts.requiredmessageid != "") {
                htmlString.push(" requiredmessageid='" + opts.requiredmessageid + "'");
            }
            if (opts.head) {
                htmlString.push(" head='" + opts.head + "'");
            }
            htmlString.push(" requiredField='" + opts.requiredField + "'");
            htmlString.push(" emptyText='" + opts.emptyText + "'");
            if (opts.autoComplete) {
                htmlString.push(" autoComplete='" + opts.autoComplete + "'");
            }
            htmlString.push(" value='" + opts.defaultText + "'");
            htmlString.push(" defaultText='" + opts.defaultText + "'");
            htmlString.push(" val='" + opts.defaultValue + "'");
            /*the defaultValue is jQuery default member, so we cannot use "defultValue", change to "defaultvalue"*/
            htmlString.push(" defaultvalue='" + opts.defaultValue + "'");
            if (opts.tabIndex != "") {
                htmlString.push(" tabIndex='" + opts.tabIndex + "'");
            }
            if (opts.disable != "") {
                htmlString.push(" disable='disable'");
            }
            if (opts.cssClass != "") {
                htmlString.push(" class='" + opts.cssClass + "'");
            }
            //add events
            if (opts.onClick) {
                htmlString.push(" onClick='" + opts.onClick + "'");
            }
            if (opts.onClickItem) {
                htmlString.push(" onClickItem='" + opts.onClickItem + "'");
            }

            if (opts.isListOverflow) {
                htmlString.push("/></div></div><div class='item_sublist overflow hide'>");
            }
            else {
                htmlString.push("/></div></div><div class='item_sublist hide'>");
            }
            if (opts.height != "") {
                htmlString.push("<ul style='max-height:" + opts.height + ";'>");
            }
            else {
                htmlString.push("<ul>");
            }
            $.each(opts.data, function (key, value) {
                htmlString.push("<li val='" + key + "'>" + value + "</li>");
            });
            htmlString.push("</ul></div></div>");
            if (opts.errorControl && opts.requiredField > -1) {
                htmlString.push("<div class='txtError hide' validate_error='" + opts.id + "'");
                if (opts.defaultErrorMessage != "") {
                    htmlString.push(" default_error_message='" + opts.defaultErrorMessage + "'");
                }
                if (opts.requireErrorMessage != "") {
                    htmlString.push(" require_error_message='" + opts.requireErrorMessage + "'");
                }
                htmlString.push("></div>");
            }
            //Choose html add method: append/html/prepend
            switch (opts.action) {
                case "append": { $dropDownlists = $(this).append(htmlString.join("")); break; }
                case "before": { $dropDownlists = $(this).before(htmlString.join("")); break; }
                case "after": { $dropDownlists = $(this).after(htmlString.join("")); break; }
                case "html": { $(this).find("*").remove(); $dropDownlists = $(this).html(htmlString.join("")); break; }
                case "prepend": { $dropDownlists = $(this).prepend(htmlString.join("")); break; }
                case "replaceWith": { $dropDownlists = $(this).replaceWith(htmlString.join("")); break; }
                case "": { $dropDownlists = $(htmlString.join("")); break; }
            }

            /*after create dropdownlist*/
            if (opts.onLoad != "") {
                $dropDownlists.each(function () {
                    opts.onLoad($(this));
                });
            }
            /*dropdownlist click*/
            if (opts.onClick != "") {
                $dropDownlists.each(function () {
                    $(this).find("input").click(
                        function () {
                            opts.onClick($(this));
                        }
                    );
                });
            }
            /*dropdownlist selected text change*/
            if (opts.onTextChange != "") {
                $dropDownlists.each(function () {
                    $(this).find("input").change(
                        function () {
                            opts.onTextChange($(this));
                        }
                    );
                });
            }
            /*dropdownlist item click*/
            if (opts.onClickItem != "") {
                DropDownListClickEvents[opts.id] = opts.onClickItem;
            }

            /*dropdownlist item mouseleave*/
            if (opts.onMouseleave != "") {
                DropDownListMouseleaveEvents[opts.id] = opts.onMouseleave;
            }

            /*dropdownlist item mouseover*/
            if (opts.onMouseover != "") {
                DropDownListMouseoverEvents[opts.id] = opts.onMouseover;
            }

            /*dropdownlist item key press*/
            if (opts.onKeyDown != "") {
                DropDownListKeyDownEvents[opts.id] = opts.onKeyDown;
            }

            /*dropdownlist item key press*/
            if (opts.onKeyPress != "") {
                DropDownListKeyPressEvents[opts.id] = opts.onKeyPress;
            }

            /*dropdownlist item key up*/
            if (opts.onKeyUpItem != "") {
                DropDownListKeyUpEvents[opts.id] = opts.onKeyUpItem;
            }

            /*dropdownlist mouseover*/
            if (opts.onMouseover != "") {
                $dropDownlists.each(function () {
                    $(this).find("input").mouseover(
                        function () {
                            opts.onMouseover($(this));
                        }
                    );
                });
            }
            /*dropdownlist mouseleave*/
            if (opts.onMouseleave != "") {
                $dropDownlists.each(function () {
                    $(this).find("input").mouseleave(
                        function () {
                            opts.onMouseleave($(this));
                        }
                    );
                });
            }
            /*dropdownlist key down*/
            if (opts.onKeyDown != "") {
                $dropDownlists.each(function () {
                    $(this).find("input").keydown(
                        function () {
                            opts.onKeyDown($(this));
                        }
                    );
                });
            }
            /*dropdownlist key press*/
            if (opts.onKeyPress != "") {
                $dropDownlists.each(function () {
                    $(this).find("input").keypress(
                        function () {
                            opts.onKeyPress($(this));
                        }
                    );
                });
            }
            /*dropdownlist key down*/
            if (opts.onKeyUp != "") {
                $dropDownlists.each(function () {
                    $(this).find("input").keyup(
                        function () {
                            opts.onKeyUp($(this));
                        }
                    );
                });
            }
        }
    });
    return $dropDownlists;
};

// Custom button
$.fn.CustomButton = function (options) {
    var defaults =
          {
              action: "append", //append, html, prepend ,after, before,replaceWith,""
              id: "CustomButton",
              text: "button",
              width: 60,
              tabIndex: 0,
              href: "",
              onclick: null,
              onmouseover: null,
              onmouseout: null
          };
    var opts = $.extend(defaults, options);
    var htmlString = new Array("");
    htmlString.push("<div class='button'><div class='button_first'><div class='button_last'");
    htmlString.push(" style='min-width:" + opts.width + ";'>");
    htmlString.push("<a id='" + opts.id + "' tabIndex='" + opts.tabIndex + "'");
    if (opts.href != "") {
        htmlString.push(" href='" + opts.href + "'");
    }
    htmlString.push(">" + opts.text + "</a></div></div></div>");
    //Choose html add method: append/html/prepend
    switch (opts.action) {
        case "append": { $(this).append(htmlString.join("")); break; }
        case "before": { $(this).before(htmlString.join("")); break; }
        case "after": { $(this).after(htmlString.join("")); break; }
        case "html": { $(this).find("*").remove(); $(this).append(htmlString.join("")); break; }
        case "prepend": { $(this).prepend(htmlString.join("")); break; }
        case "replaceWith": { $(this).replaceWith(htmlString.join("")); break; }
        case "": { $(htmlString.join("")); break; }
    }
    if (opts.onclick) {
        $(this).click(opt.onclick);
    }
    if (opts.onmouseover) {
        $(this).mouseover(opts.onmouseover);
    }
    if (opts.onmouseout) {
        $(this).mouseout(opts.onmouseout);
    }
}

// This div will be transformed to the pop-up
var sessionEndPanel = "<div id='sessionEndDialog' title='Session Expiring'><p>Your Session is about to expire. Click OK to renew your session or Logout to logout of the application.</p></div>";

//--------------T-grid default event---------------
//T-grid OnDataBinding
function OnDefaultDataBinding() {
    loadingPanel();
}
//T-grid OnDataBound
function OnDefaultDataBound() {
    unloadingPanel();
}
//T-grid OnError
function OnDefaultError() {
    unloadingPanel();
}

//--------------On Grid Error--------------- 
function onGridError(e) {
    unloadingPanel();
    $("html").ShowError({
        showType: "tgrid",
        ex: e
    });
}

function onCTPError(jsonError) {
    return jsonError.ErrorMessage;
}

//--------------On Application Error---------------
function onApplicationError(e) {
    // This div will be used to display an error message.
    var errorPanel = "<div id='errorDialog' title='Error'><p>" + e + "</p></div>";
    $(errorPanel).dialog({
        draggable: false,
        resizable: false,
        modal: true,
        buttons: [{
            text: "OK",
            click: function () {
                $(this).dialog("close");
            }
        }]
    });
}

//Show the tip
function hideTip() {
    $("#tipCss").addClass("hide");
}

//Hide the tip
function showTip(left, top, tipHeader, tipContent) {
    if (tipHeader)
        $("#tipHeader").text(tipHeader);
    if (tipContent)
        $("#tipContent").text(tipContent);

    $("#tipCss").removeClass("hide");

    $("#tipCss").css("left", left + "px");
    $("#tipCss").css("top", top + "px");
}

//---------------Add tab index------------------------------
$.fn.AddTabIndex = function (index) {
    $(this).each(function () {
        $(this).find("input, a, select, textarea").each(function () {
            $(this).attr("tabIndex", index);
            index++;
        });
    });
}

//---------------Add tip event------------------------------
function Addtip(selector, corY, showEvent, hideEvent) {
    $(selector).live(showEvent, function (e) {
        //get head and text
        var text = "";
        var head = "";
        if ($(this).attr("head")) {
            head = $(this).attr("head");
        }
        if ($(this).attr("tip")) {
            text = $(this).attr("tip");
        }
        var error_disable = GetLocalFieldByID("error_disable");
        if ($(this).attr("disabled")) {
            text = error_disable;
        }
        //get  left and top
        var position = $(this).offset();
        var x = position.left + $(this).width();
        var y = position.top;
        if (text)
            showTip(x, y, head, text);
    });
    $(selector).live(hideEvent, function () {
        hideTip();
    });
}

//----------------get localization info by id [text]---------------
function GetLocalFieldByID(id, prefix) {
    var selectString = "";
    if (typeof (prefix) == "undefined" || prefix == "") {
        prefix = "field";
    }

    if (localInfoSrc != undefined) {1
        selectString = prefix + "[id='" + id + "']";
        selectString = $(localInfoSrc).find(selectString).text();
    }
    return selectString;
}

//----------------get localization info by id [json]---------------
function GetLocalJsonByID(id) {
    var selectString = {};
    if (localInfoSrc != undefined) {
        selectString = "json[id='" + id + "']";
        selectString = $(localInfoSrc).find(selectString).text();
    }
    return eval("(" + selectString + ")");
}


//----------------modal dialog-------------------
//show html tag which has class "modal" in a modal dialog and hide it 
function Dialog(selector) {
    if ($(selector).hasClass("hide")) {
        showModal();
        $(selector).removeClass("hide");
    }
    else {
        hideModal();
        $(selector).addClass("hide");
    }
}

//show lodingPanenl 
function loadingPanel() {
    if (!$("#modal").hasClass("loading")) {
        $("#modal").addClass("loading");
        $("body").attr("loading", "true");
        showModal();
    }
    timeout();
    //this code may have some issue.
    //    $("a[id]").each(function (index, value) {
    //        var id = value.id;
    //        // Avoid some of button haven't set id attribute.
    //        if (id == "") return;
    //        // Whether focus id equals the current iteration id.
    //        if (document.activeElement.id == id) {
    //            _Current_ID_ = id;
    //            $("#" + id).focusout();
    //            $("#" + id).attr("disabled", true);
    //        }
    //    });
}

var _TIME_ID_;

function timeout() {
    clearTimeout(_TIME_ID_);
    _TIME_ID_ = setTimeout("unloadingPanel();", 60000);
}

function unloadingPanel() {
    $('#modal').removeClass('loading');
    $("body").removeAttr("loading");
    hideModal();
    if (_Current_ID_ != "") {
        //Set enabled and focus to current selected button.
        $("#" + _Current_ID_).attr("disabled", false);
        $("#" + _Current_ID_).focus();
        _Current_ID_ = "";
    }
}

//show modal lay
function showModal() {
    $("#modal").css("height", $(document).height());
    $("#modal").addClass("visible");
}
//hide modal lay
function hideModal() {
    $("#modal").removeClass("visible");
}

//--------------session timeout--------------- 
function scheduleSessionPrompt() {
    if (logoutTimer) clearTimeout(logoutTimer);
    if (sessionTimer) clearTimeout(sessionTimer);
    sessionTimer = setTimeout(sessionExpiring, sessionTimeout);
}

function sessionExpiring() {
    logoutTimer = setTimeout(logoutOnSessionExpires, sessionDialogWait);
    $(sessionEndPanel).dialog({
        draggable: false,
        resizable: false,
        modal: true,
        buttons: [{
            text: "OK",
            click: function () {
                $(this).dialog("close");
                scheduleSessionPrompt();
            }
        }]
    });
}

//dropdownlist switch language
function onComboBoxChange(e) {
    var url = e.value;
    window.location.href(url);
}
$("#ddlchangelang").change(function (e) {
    var url = e.value;
    window.location.href(url);
    loadingPanel();
});

//Set Dropdownlist scroll
function scroll(list, active) {
    active = active.get(0);
    list = list.get(0);
    if (active.offsetTop + active.offsetHeight > list.scrollTop + list.clientHeight) {
        list.scrollTop = active.offsetTop + active.offsetHeight - list.clientHeight;
    }
    else if (active.offsetTop < list.scrollTop) {
        list.scrollTop = active.offsetTop;
    }
}


//Set Dropdownlist select item
function selectItem(ddlNode, keyCode) {
    if (keyCode == Enter) {
        $(ddlNode).find("div[class~='item_sublist']").toggleClass("hide");
    }
    else if (keyCode == Tab) {
        $(ddlNode).find("div[class~='item_sublist']").addClass("hide");
    }
    else
        if (keyCode == KeyUP || keyCode == KeyDown) {
            $(ddlNode).find("div[class~='item_sublist']").removeClass("hide");
            var index = $(ddlNode).find("li").index($(ddlNode).find("li.selected"));
            $(ddlNode).find("li.selected").removeClass("selected");
            var length = $(ddlNode).find("li").length;
            switch (keyCode) {
                case KeyUP:
                    {
                        if (index > 0) {
                            index--;
                        }
                        break;
                    }
                case KeyDown:
                    {
                        if (index < length - 1) {
                            index++;
                        }
                        break;
                    }
            }
            var selectli = "li:eq(" + index + ")";
            $(ddlNode).find(selectli).addClass("selected");
            scroll($(ddlNode).find("ul:eq(0)"), $(ddlNode).find("li.selected:eq(0)"));
        }
    if ($(ddlNode).find("li.selected").length > 0) {
        var value = $(ddlNode).find("li.selected").attr("val");
        var text = $(ddlNode).find("li.selected").text();

        $(ddlNode).find("input:eq(0)").attr("val", value);
        $(ddlNode).find("input:eq(0)").attr("value", text);

        var hidden = $(ddlNode).find(":hidden:eq(0)");
        if (hidden != null) {
            hidden.attr("val", value);
            hidden.attr("value", value);
        }
    }
}

//Set Dropdownlist select item 
function selectItemExt($ddlNode, keyCode) {
    if (keyCode == Tab || keyCode == Esc) {
        $("#common_sublist").addClass("hide");
        return;
    }
    if (keyCode == KeyUP || keyCode == KeyDown) {
        if ($("#common_sublist").hasClass("hide")) {
            $ddlNode.find("input").click();
        }
        else {
            var index = $("#common_sublist").find("li").index($("#common_sublist").find("li.selected"));
            $("#common_sublist").find("li.selected").removeClass("selected");
            var length = $("#common_sublist").find("li").length;
            switch (keyCode) {
                case KeyUP:
                    {
                        if (index > 0) {
                            index--;
                        }

                        break;
                    }
                case KeyDown:
                    {
                        if (index < length - 1) {
                            index++;
                        }

                        break;
                    }
            }
            if (index != -1) {
                var selectli = "li:eq(" + index + ")";
                $("#common_sublist").find(selectli).addClass("selected");
                scroll($("#common_sublist").find("ul:eq(0)"), $("#common_sublist").find("li.selected:eq(0)"));
            }
        }
        return;
    }

    if (keyCode == Enter) {
        if ($("#common_sublist").hasClass("hide")) {
            $ddlNode.find("input").click();
        }
        else {
            if ($("#common_sublist li.selected").length > 0) {
                $("#common_sublist li.selected").click();
            }
            else {
                $("#common_sublist").addClass("hide");
            }
        }
    }

}

/*refactor version*/
function GetTargDropDownList() {
    return $("#" + $("#common_sublist").attr("targetId")).closest(".custom_dropdownlist");
}

function isRefactorVersion(element) {
    if (($(element).closest(".custom_dropdownlist").attr("refactorVersion") && $(element).closest(".custom_dropdownlist").attr("refactorVersion")) == "true" || ($(element).closest(".custom_dropdownlist").find("input").attr("refactorVersion") && $(element).closest(".custom_dropdownlist").find("input").attr("refactorVersion") == "true")) {
        return true
    }
    else {
        return false;
    }
}

//---------validate textbox---------
function validate(type, value) {
    var reg;
    var ispassed = "pass";
    switch (type) {
        case 'double': { reg = /^[0-9]*$/; if (!reg.test(value)) { ispassed = GetLocalFieldByID("error_input_number"); } break; }
        case 'name': { reg = /^[^%*@#$!~^]*$/; if (!reg.test(value)) { ispassed = GetLocalFieldByID("error_input_name"); } break; }
        case 'normalChar': { reg = /^[^%*@#$!~^]*$/; if (!reg.test(value)) { ispassed = GetLocalFieldByID("error_input_specialChar"); } break; }
        case 'word': { reg = /^[^0-9%*@#$!~]*$/; if (!reg.test(value)) { ispassed = GetLocalFieldByID("error_input_word"); } break; }
        case 'money': { reg = /^([1-9][0-9]*|[0-9])(\.[0-9]{1,2})?$/; if (!reg.test(value)) { ispassed = GetLocalFieldByID("error_input_money"); } break; }
        case 'number': { reg = /^[0-9]*$/; if (!reg.test(value)) { ispassed = GetLocalFieldByID("error_input_number"); } break; }
        case 'phonenumber': { reg = /^[\d-.\s]+$/; if (!reg.test(value)) { ispassed = GetLocalFieldByID("error_input_phonenumber"); } break; }
        case 'prefixnumber': { reg = /^[0-9.\s-]+$/; if (!reg.test(value)) { ispassed = GetLocalFieldByID("error_input_prefixnumber"); } break; }
        case 'tokenid': { reg = /^[a-zA-Z0-9]{1}([a-zA-Z0-9]|[-|\s]){11,28}$/; if (!reg.test(value)) { ispassed = GetLocalFieldByID("error_input_tokenid"); } break; }
        case 'email': { reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/; if (!reg.test(value)) { ispassed = GetLocalFieldByID("error_input_liveid"); } break; }
        case 'string': { break; }
        default: { ispassed = eval(type); }
    }
    return ispassed;
}

//---------------Accessibility-----------
function Accessibility() {
}
Accessibility.prototype.init = function () {
    $("a").live("focus", function (event) {
        if (!$(this).hasClass("t-state-disabled") && !$(this).hasClass("hide")) {
            $(this).addClass("focus");
        }
    });
    $("a").live("focusout", function (event) {
        $(this).removeClass("focus");
    });
}

var accessibilityPager = new Accessibility();

var localInfoSrc = {};
var pageLang = "en-us";

//---------------default initial-----------
function Default() {

    //set session timeout
    //scheduleSessionPrompt();
    //set locoalization info by lang
    if ($("head[lang]:eq(0)").attr("lang") != undefined) {
        pageLang = $("head[lang]:eq(0)").attr("lang");
    }
    GetXMLFileByAjax(pageLang, "en-us",
        function (xml) {
            localInfoSrc = xml;
        }
    );

    //when focus on a linke, the linke will have outline
    accessibilityPager.init();

    //Button focus style
    $("div.button a").live("focusin", function () {
        $(this).parents("div.button:eq(0)").addClass("button_focus");
    });

    $("div.button a").live("focusout", function () {
        $(this).parents("div.button:eq(0)").removeClass("button_focus");
    });

    //When focusout add validate textbox event , the textbox no input , set to default
    $(".input_text input[validatetype], .custom_input input[validatetype]").live("focusout", function (event) {
        $(this).attr("value", $.trim($(this).attr("value")));
        var $validate_error = $("[validate_error='" + $(this).attr("id") + "']");
        if (!$(this).hasClass("textTip") && $(this).attr("value") != "") {
            var validatetype = $(this).attr("validatetype");
            var value = $(this).attr("value");
            var validateInfo = validate(validatetype, value);
            if (validateInfo != "pass") {
                $(this).addClass("inputerror");
                if ($validate_error.attr("type_error_message") != undefined && $validate_error.attr("type_error_message") != null && $validate_error.attr("type_error_message") != "undefined") {
                    $validate_error.removeClass("hide").text($validate_error.attr("type_error_message"));
                } else {
                    if ($validate_error.attr("default_error_message") != undefined && $validate_error.attr("default_error_message") != null && $validate_error.attr("default_error_message") != "undefined") {
                        $validate_error.removeClass("hide").text($validate_error.attr("default_error_message"));
                    }
                    else {
                        $validate_error.removeClass("hide").text(validateInfo);
                    }
                }
            }
            else {
                if ($(this).hasClass("inputerror")) {
                    $(this).removeClass("inputerror");
                    $validate_error.addClass("hide").text("");
                }
            }
            if ($(this).hasClass("maxLength") && $(this).text().length <= $(this).attr("maxLength")) {
                $(this).attr("tip", GetLocalFieldByID("error_input_length"));
            }
        }
        // textTip is unique
        else {
            if ($(this).attr("head")) {
                $(this).addClass("textTip");
                $(this).attr("value", $(this).attr("head"));
            }
            $(this).removeClass("inputerror");
            $validate_error.addClass("hide").text("");
        }
    });


    //When focus on the text box, clear the default tip in the textbox
    $(".input_text input, .custom_input input").live("focus", function (event) {
        if ($(this).hasClass("textTip")) {
            $(this).attr("value", "");
            $(this).removeClass("textTip");
        }
    });

    //Add validate textarea event
    $("textarea[maxLength]").live("keydown", function (event) {
        if ((event.ctrlKey && event.keyCode == 86) || (!event.ctrlKey)) {//  ctrlKey || ctrlKey+S
            if ($(this).text().length >= parseInt($(this).attr("maxLength"))) {
                var tempString = $(this).text().substr(0, $(this).attr("maxLength"));
                $(this).text(tempString);
            }
        }

    });
    $("textarea[maxLength]").live("keyup", function (event) {
        if ((event.ctrlKey && event.keyCode == 86)) {//  ctrlKey || ctrlKey+S
            if ($(this).text().length >= parseInt($(this).attr("maxLength"))) {
                var tempString = $(this).text().substr(0, $(this).attr("maxLength"));
                $(this).text(tempString);
            }
        }
    });

    //-------------datepicker
    var monthName = GetLocalFieldByID("month_name").split(',');

    $(".datepicker").find("input").each(function () {
        var inputEle = this;
        $(this).parents(".datepicker:eq(0)").click(function () {
            inputEle.focus();
        });
        $(this).datepicker({
            changeYear: true,
            changeMonth: true,
            monthNamesShort: monthName
        });
        $(this).attr("value", $(this).attr("defaultDate"));
    });

    //-------------Main Menu Event
    //-------------menu selected
    var menuValue = $("title[id]").attr("id");
    switch (menuValue) {
        case "customerSearchPage": { $("div.top_menu ul li:eq(0)").addClass("selectedItem"); $("#button_search").focus(); break; }
        case "commentPage":
            {
                // Reuse case customerOverviewPage.
            }
        case "customerOverviewPage": { $("div.top_menu ul li:eq(1)").addClass("selectedItem"); $("#button_customer").focus(); break; }
        case "transactionPage": { $("div.top_menu ul li:eq(2)").addClass("selectedItem"); $("#btn_transaction").focus(); break; }
        case "subscriptionPage": { $("div.top_menu ul li:eq(3)").addClass("selectedItem"); $("#btn_subscription").focus(); break; }
        case "paymentInstrumentPage": { $("div.top_menu ul li:eq(4)").addClass("selectedItem"); $("#btn_payment").focus(); break; }
        case "pointPage": { $("div.top_menu ul li:eq(5)").addClass("selectedItem"); $("#btn_pointPage").focus(); break; }
        case "lookupPrepaidCard":
            {
                //Set mainmenu highlight.
                if (parseBoolean($("#PrepaidCard").attr("data-isCustomerSearch"))) {
                    $("div.top_menu ul li:eq(0)").addClass("selectedItem");
                    $("#button_search").focus();
                } else {
                    $("div.top_menu ul li:eq(1)").addClass("selectedItem");
                    $("#button_customer").focus();
                }
                break;
            }
        case "banOrUnbanPage":
            {
                //Set mainmenu highlight.
                if (parseBoolean($("#pnlMain").attr("data-isCustomerSearch"))) {
                    $("div.top_menu ul li:eq(0)").addClass("selectedItem");
                    $("#button_search").focus();
                } else {
                    $("div.top_menu ul li:eq(1)").addClass("selectedItem");
                    $("#button_customer").focus();
                }
                break;
            }
        default:
            {
                //for every page initial focus on the  search button
                $("#button_search").focus();
                break;
            }
    }
    //-------------mouseover of menu
    $(".button_list_top li a").hover(
        function () {
            if ($(this).is(":not([disabled])"))
                $(this).parents("li:eq(0)").addClass("hoverItem");
        },
        function () {
            if ($(this).is(":not([disabled])"))
                $(this).parents("ul").find("li").removeClass("hoverItem");
        }
    );
    //-------------active of menu
    $(".button_list_top li a").focus(function () {
        if ($(this).is(":not([disabled])"))
            $(this).parents("li:eq(0)").addClass("activeItem");
    });
    $(".button_list_top li a").focusout(function () {
        if ($(this).is(":not([disabled])"))
            $(this).parents("ul").find("li").removeClass("activeItem");
    });

    //-------------Custom Dorpdownlist Comment Event
    /*refactor version*/
    function clickCommonSublist() {

    }
    $("#common_sublist li").live("click", function () {
        var $selectDrop = GetTargDropDownList();
        $("#common_sublist").addClass("hide");
        $selectDrop.find("input:eq(0)").removeClass("inputerror");
        $selectDrop.find("input:eq(0)").attr("val", $("#common_sublist").find("li.selected").attr("val"));
        $selectDrop.find("input:eq(0)").attr("value", $("#common_sublist").find("li.selected").text());
        if (DropDownListClickEvents && DropDownListClickEvents[$("#common_sublist").attr("targetId")]) {
            DropDownListClickEvents[$("#common_sublist").attr("targetId")]($selectDrop);
        }
    });

    $("html").live("mousedown", function (e) {
        if ($(e.target).closest("#common_sublist").length > 0) {
            if (e.target.tagName == "LI") {
                $("#common_sublist").find("li.selected").click();
            }
        }
        else {
            $("#common_sublist").addClass("hide");
        }
    });

    $("*").scroll(function (e) {
        if ($(e.target).closest("#common_sublist").length == 0) {
            $("#common_sublist").addClass("hide");
        }
    });

    $("#common_sublist ul li").live("mouseover", function () {
        $(this).siblings("li.selected").removeClass("selected");
        $(this).addClass("selected");
        if (DropDownListMouseoverEvents[$("#common_sublist").attr("targetId")]) {
            DropDownListMouseoverEvents[$("#common_sublist").attr("targetId")]($selectDrop);
        }
    });
    // When foucus out, recover the data list
    $(".custom_dropdownlist input").live('focus', function () {
        var $selectDrop = $(this).closest(".custom_dropdownlist");
        $("#common_sublist").find("ul").html($selectDrop.find("ul").html());
        $("#common_sublist").attr("targetId", $selectDrop.find("input[id]:eq(0)").attr("id"));
        if ($(this).attr("emptyText")) {
            $("#common_sublist").find("ul").prepend("<li val=''>" + $(this).attr("emptyText") + "</li>");
        }
    });
    // intercept the keyboard event for filter (auto complete only for refactor version)
    $(".custom_dropdownlist input").live('keydown', function (e) {
        var $selectDrop = $(this).closest(".custom_dropdownlist");
        if ($(this).attr("autoComplete") && $(this).attr("autoComplete") == "true" && isRefactorVersion(this)) {

            // Make sure it's a-z char
            if (e.keyCode && e.keyCode >= 65 && e.keyCode <= 90) {
                var c = String.fromCharCode(e.keyCode);
                var listdata = "";
                if ($selectDrop.find("ul li").length > 0)
                    $selectDrop.find("ul li").each(function (index, item) {
                        if ($(this).text().indexOf(c) == 0) {
                            listdata += this.outerHTML;
                        }
                    });
                if (listdata != "") {
                    $("#common_sublist").find("ul").html("");
                    $("#common_sublist").find("ul").append(listdata)
                }
            }
            else if (e.keyCode == 8) {
                $("#common_sublist").html($selectDrop.find(".item_sublist").html());

                // back sapce, stop the default browser behavior.
                if ($(this).is("[readOnly]")) {
                    if (e.preventDefault) {
                        e.preventDefault();
                    }
                    else {
                        return false;
                    }
                }
            }

        }
    });

    //-------------dorpdownlist shortcut
    $(".custom_dropdownlist input").live("keydown", function (e) {
        if (!$(this).is("[disabled]")) {
            var $selectDrop = $(this).closest(".custom_dropdownlist");
            /*refactor version*/
            if (isRefactorVersion(this)) {
                selectItemExt($selectDrop, e.keyCode);
            }
            /*old version*/
            else {
                selectItem($selectDrop, e.keyCode);
            }
        }
    });
    $(".custom_dropdownlist").live("hover", function () {
        if (!$(this).find("input").is("[disabled]")) {
            $(this).toggleClass("custom_dropdownlist_hover");
        }
    });

    //-------------dorpdownlist itemlist show
    $(".r_custom_dropdownlist").live("click", function () {
        if ($(this).find("input[disabled]").length == 0) {
            var $selectDrop = $(this).closest(".custom_dropdownlist");
            /*refactor version*/
            if (isRefactorVersion(this)) {
                var tempWidth = $selectDrop.outerWidth();
                var tempX = $selectDrop.offset().left;
                var tempY = $selectDrop.offset().top + $selectDrop.find("input").outerHeight();
                $("#common_sublist").css("width", tempWidth + "px");
                $("#common_sublist").css("left", tempX + "px");
                $("#common_sublist").css("top", tempY + "px");
                if ($("#common_sublist").hasClass("hide")) {
                    $("#common_sublist").removeClass("hide");
                }
                else {
                    $("#common_sublist").addClass("hide");
                }
                var $currentObj = $(this).find("input");
                var funcName = $currentObj.attr("onSelectItem");
                if (funcName != null && funcName != undefined) {
                    var id = $currentObj.attr("id");
                    eval(funcName + "(" + jsonToString({ "targetId": id }) + ")");
                }
            }
            /*old version*/
            else {
                if ($selectDrop.find("div[class~='item_sublist']").hasClass("hide")) {
                    $selectDrop.find("div[class~='item_sublist']").removeClass("hide");
                }
                else {
                    $selectDrop.find("div[class~='item_sublist']").addClass("hide");
                }
            }
            $(this).find("input").focus();
        }
    });
    /*refactor version end*/

    //-------------dorpdownlist change value and itemlist hide
    $(".custom_dropdownlist li").live("click", function () {
        var selectDrop = $(this).parents(".custom_dropdownlist:eq(0)");
        if ($(selectDrop).find("li.selected").length > 0) {
            $(selectDrop).find("input:eq(0)").attr("val", $(this).attr("val"));
            $(selectDrop).find("input:eq(0)").attr("value", $(this).text());

            var hidden = $(selectDrop).find(":hidden:eq(0)");
            if (hidden != null) {
                hidden.attr("val", $(this).attr("val"));
                hidden.attr("value", $(this).attr("val"));
            }
        }
        $(selectDrop).find("div[class~='item_sublist']").addClass("hide");
    });

    $(".custom_dropdownlist").live("mouseleave", function () {
        $(this).find("div[class~='item_sublist']").addClass("hide");
    });

    $("div[class*='item_sublist'] ul li").live("mouseover", function () {
        $(this).siblings("li.selected").removeClass("selected");
        $(this).addClass("selected");
    });

    //button and link keydown == enter
    $("span[tabindex],a[tabindex]").live("keydown", function (e) {
        if (e.keyCode == Enter && !$(this).is("[href]") && !$("#modal").hasClass("loading")) {
            $(this).click();
        }
    });

    //textarea maxlength validate
    $("textarea[maxLength]").live("focus", function (event) {
        removeDefaultTextOnElement("#" + this.id);
    });

    //-------------custom check box
    $("[class~='plusChk']").live('click', function () {
        $(this).toggleClass('checked');
    });

    //-------------make all the href link will loading when click
    //    $("a[href]").click(function () {
    //        if (!$(this).is("[href^='#']")) {
    //            loadingPanel();
    //        }
    //    });

    /*Solution 1*/
    $("html").keydown(function (e) {
        if (e.keyCode == Tab || e.keyCode == tabback) {
            var notNext = true;
            var tempelement = new Object();
            $("a:visible,input:visible,textarea:visible").each(function () {
                if ($(this).closest("[disabled]").length == 0) {
                    if (tempelement != null) {
                        if (notNext) {
                            if ($(this).is(":focus")) {
                                if (e.keyCode == tabback) {
                                    if (tempelement instanceof jQuery) {
                                        tempelement.focus();
                                    }
                                    return false;
                                }
                                else {
                                    notNext = false;
                                }
                            }
                            else {
                                tempelement = $(this);
                            }
                        }
                        else {
                            $(this).focus();
                            return notNext;
                        }
                    }
                }
            });
            return notNext;
        }
    });

    //-----------After master page default initail do the patial page initail function
    if (initialView) {
        initialView();
    }
    $("html").keydown(function (e) {
        if ($(this).is("[loading]")) {
            return false;
        }
    });
    $("html").keypress(function () {
        if ($(this).is("[loading]")) {
            return false;
        }
    });
    $("html").keyup(function () {
        if ($(this).is("[loading]")) {
            return false;
        }
    });
}

//--------------Handle error---------------
function HandleError(response) {
    this._response = response;
}
HandleError.prototype.message = function (f) {
    this._message = f;
    return this;
}
HandleError.prototype.redirect = function (f) {
    if (typeof f == "string") {
        this._redirect = function () {
            window.location = f;
        }
    }
    else {
        this._redirect = f;
    }
    return this;
}
HandleError.prototype.handle = function () {
    if (this._response.redirect == true) {
        if (this._redirect) {
            this._redirect();
        }
        else {
            window.location = "/";
        }
    }
    else {
        this._message(this._response.responseText);
    }
}
//--------------Handle Json error---------------
function showJsonDataGridError(id, error) {
    var grid = $(id).data('tGrid');
    if (grid != null || grid != undefined) {
        grid.total = 0;
        grid.dataBind(Array());
        new HandleError(error)
        .message(function (msg) {
            $(id).find('.t-no-data td').text(getErrorMsg(msg));
        }).handle();
    }
}
function getErrorMsg(error) {
    return ($.parseJSON(error)).message;
}

//-------------datepicker only mmYYYY
function CustomerDatePic(Id, mmYYYY) {
    var defaultMonth = mmYYYY.split("/")[0];
    var defaultYear = mmYYYY.split("/")[1];
    var ddlHtml = "<table class=\"dateTable\"><tr>";

    var opt = {};
    opt["action"] = "";
    opt["refactorVersion"] = true;
    opt["requiredField"] = 1;
    opt["readOnly"] = false;

    //------generate date------
    var month = {};
    var year = {};
    var dateNow = new Date();
    var currentYear = (dateNow.getYear() < 1900) ? (1900 + dateNow.getYear()) : dateNow.getYear();

    for (var i = 1; i <= 12; i++) {
        if (i < 10) {
            month[i] = "0" + i.toString();
        }
        else {
            month[i] = i;
        }
    }
    for (var i = currentYear; i < currentYear + 99; i++) {
        year[i] = i;
    }

    //------generate month------
    opt["id"] = "ddlMonth_" + Id;
    opt["defaultText"] = defaultMonth;
    opt["defaultValue"] = defaultMonth;
    opt["width"] = "50px";
    opt["data"] = month;
    ddlHtml = ddlHtml + "<td class=\"tdMonth\">";
    //    ddlHtml = ddlHtml + CustomeDropDownList("ddlMonth", "ddlMonth_" + Id, defaultMonth, "50px");
    ddlHtml = ddlHtml + $("#tb_Date").CustomDropDownList(opt)[0].outerHTML;
    ddlHtml = ddlHtml + "<td width=5>/</td>";
    ddlHtml = ddlHtml + "<td class=\"tdYear\">";

    //------generate year------
    opt["id"] = "ddlYear_" + Id;
    opt["defaultText"] = defaultYear;
    opt["defaultValue"] = defaultYear;
    opt["width"] = "65px";
    opt["data"] = year;
    ddlHtml = ddlHtml + $("#tb_Date").CustomDropDownList(opt)[0].outerHTML;
    ddlHtml = ddlHtml + "</td>";
    ddlHtml = ddlHtml + "<tr></table>";
    return ddlHtml;
}

function parseBoolean(booleanString) {
    if (booleanString != null && $.trim(booleanString).toLowerCase() == "true") {
        return true;
    }
    return false;
}

function removeDefaultTextOnElement(element) {
    if ($(element).hasClass("textTip")) {
        $(element).attr("value", "");
        $(element).removeClass("textTip");
    }
}

function isDefaultTextOnElement(element) {
    if ($(element).hasClass("textTip")) {
        return true;
    }
    return false;
}

function GetToken() {
    var antiForgeryToken = $("input[name=__RequestVerificationToken]").val();
    return antiForgeryToken;
}

//This extend method is used for html string decode.
$.decode = function (value) {
    var converter = document.createElement("div");
    converter.innerHTML = value;
    var result = converter.innerText;
    converter = null;
    return result;
};

$.fn.extend({
    disableSelection: function () {
        this.each(function () {
            if (typeof this.onselectstart != 'undefined') {
                this.onselectstart = function () { return false; };
            }
        });
    },
    //This method is used for space etc. special HTML character set.
    valDecode: function (value) {
        var converter = document.createElement("div");
        converter.innerHTML = value;
        this.val(converter.innerText);
        converter = null;
        return this;
    }
});

function arrayToString(arrayObject) {
    var str = [];
    for (var key in arrayObject) {
        str.push(jsonToString(arrayObject[key]));
    }

    return "[" + str.join(',') + "]";
}

function jsonObjectToString(jsonObject) {
    var str = [];
    for (var key in jsonObject) {
        str.push("\"" + key + "\"" + ":" + jsonToString(jsonObject[key]));
    }

    if (str.length > 0) {
        return "{" + str.join(',') + "}";
    }
    else {
        return "{}";
    }
}

function jsonToString(jsonObject) {
    if (jsonObject == undefined || jsonObject == null) {
        return null;
    }
    else if (jsonObject instanceof Array) {
        return arrayToString(jsonObject);
    }
    else if (typeof (jsonObject) == "object") {
        return jsonObjectToString(jsonObject);
    }
    else {
        return "\"" + jsonObject.toString().replace(/\\/g, "\\\\").replace(/\"/g, "\\\"") + "\"";
    }
}

function encodeHtml(value) {
    return $("<div/>").text(value).html();
}

function decodeHtml(value) {
    return $("<div/>").html(value).text();
}

//------------Process UICore-----------------------
$.fn.uiCore = function (options) {
    var id = $(this).attr("id");
    if (id != null && id != undefined) {
        var ctype = $(this).attr("data-ctl-type");
        if (ctype != null && ctype != undefined) {
            switch (ctype) {
                case _Ctl_CType_Button_:
                    {
                        return new CMATButton(id);
                    }
                case _Ctl_CType_CheckBox_:
                    {
                        return new CMATCheckBox(id);
                    }
            }
        }
    }
}

//------------Create Button--------------------------
// Event:       onClick
// Property:    id
// Function:    show(),hide(),enabled(),disabled(),isEnabled(),isDisabled(),setText(value),focusin(),focusout()

function CMATButton(id) {
    this.id = id;

    this.init = function (args) {

    };
}

CMATButton.prototype.onClick = function (handler) {
    $("#" + this.id).click(function () {
        handler(this);
    });
    return this;
}

CMATButton.prototype.show = function () {
    var uiGuid = $("#" + this.id).attr("data-ctl-guid");
    $("a[data-ctl-guid=" + uiGuid + "]").removeClass("hide")
    $("div[data-ctl-guid=" + uiGuid + "]").removeClass("hide");
    return this;
}

CMATButton.prototype.hide = function () {
    var uiGuid = $("#" + this.id).attr("data-ctl-guid");

    $("a[data-ctl-guid=" + uiGuid + "]").addClass("hide")
    $("div[data-ctl-guid=" + uiGuid + "]").addClass("hide");
    return this;
}

CMATButton.prototype.enabled = function () {
    $("#" + this.id).attr("disabled", false);
    return this;
}

CMATButton.prototype.disabled = function () {
    $("#" + this.id).attr("disabled", true);
    return this;
}

CMATButton.prototype.isEnabled = function () {
    return !this.isDisabled();
}

CMATButton.prototype.isDisabled = function () {
    if (parseBoolean($("#" + this.id).attr("disabled"))) {
        return true;
    } else {
        return false;
    }
}


CMATButton.prototype.setText = function (value) {
    $("#" + this.id).text(value);
    return this;
}
CMATButton.prototype.focusin = function () {
    $("#" + this.id).focusin();
    return this;
}

CMATButton.prototype.focusout = function () {
    $("#" + this.id).focusout();
    return this;
}
//------------Create Button End--------------------------

//------------Create Check Box--------------------------
// Event:       onClickEvent
// Property:    id
// Function: isChecked() check() uncheck()
$("span[class~='plusChk']").live('click', function () {
    var $currentObj = $(this);
    // change onClick to onClickEvent, IE 7 compatibility.
    var clickEvent = $currentObj.attr("onClickEvent");
    var id = $currentObj.attr("id");
    var isChecked = false;

    if ($(this).hasClass('checked')) {
        isChecked = true;
    } else {
        isChecked = false;
    }

    if (id != null && id != "") {
        // Add a state to help check box's isChecked() function.
        $currentObj.data("state", !isChecked);
        if (clickEvent != null && $.trim(clickEvent) != "") {
            // Current check box state is checked ,the next step it will change state to unchecked ,so add negated the isChecked event args.
            eval(clickEvent + "(" + jsonToString({ "targetId": id, "isChecked": !isChecked }) + ")");
        }
    }
});

function CMATCheckBox(id) {
    this.id = id;

    this.init = function (args) {

    };
}

CMATCheckBox.prototype.isChecked = function () {
    var isChecked = false;
    var $chkCurrent = $("#" + this.id);
    var currentData = $chkCurrent.data("state");
    if (currentData != undefined && currentData != null) {
        if (currentData) {
            isChecked = true;
        }
        return isChecked;
    }

    if ($chkCurrent.hasClass('checked')) {
        isChecked = true;
    } else {
        isChecked = false;
    }
    return isChecked;
}

CMATCheckBox.prototype.check = function () {
    var $currentObj = $("#" + this.id);
    var isChecked = $currentObj.uiCore().isChecked();
    if (!isChecked) {
        $currentObj.click();
    }

    return this;
}

CMATCheckBox.prototype.uncheck = function () {
    var $currentObj = $("#" + this.id);
    var isChecked = $currentObj.uiCore().isChecked();
    if (isChecked) {
        $currentObj.click();
    }

    return this;
}

//------------Create Check Box End--------------------------


function initXml() {
    //Get ZipCode XML
    $.ajax({
        url: ResourcePath + GetLocalFieldByID("dbZipPattern"),
        success: function (xml) {
            _ZipCodeXML = xml;
        }
    });
}


//Validate ZipCode
function validateZipCode(countryname, inputtext, errorId, headMessage) {
    var flag = false;
    var $obj = $(_ZipCodeXML);
    var inputLength = inputtext.replace(/[-| ]/g, "").length;
    var errorMessage = GetLocalFieldByID("wrongformat_pi_ZipCode");
    if (countryname == undefined || inputtext == "") {
        return false;
    }
    if ($obj.find("Country[text='" + countryname + "']").get(0) == undefined) {
        flag = true;
        return flag;
    }
    $obj.find("Country[text='" + countryname + "']").parent().find("Length").each(function () {
        var $obj = $(this);

        if ($obj.text() == "0") {
            flag = true;
            return true;
        }
        if (inputLength == $obj.text()) {
            var pattern = $obj.parent().find("Pattern").text();
            var regex = mapPatternToRegex(pattern);
            if (regex.test(inputtext)) {
                flag = true;
            }
        }
        if (flag == true)
            return true;
    });
    if (flag == false) {
        $("#" + errorId).text(errorMessage).addClass("inputerror");
    }
    return flag;
}

//Mapping Regex
function mapPatternToRegex(pattern) {
    var regN = /(N+)/g;
    var regA = /(A+)/g;
    var regX = /(X+)/g;
    pattern = pattern.replace(regN, function ($) {
        var len = $.length;
        if (len == 1) {
            return '\\d';
        }
        return '\\d{' + len + '}'
    });

    pattern = pattern.replace(regA, function ($) {
        var len = $.length;
        if (len == 1) {
            return '[a-zA-Z]';
        }
        return '[a-zA-Z]{' + len + '}'
    });

    pattern = pattern.replace(regX, function ($) {
        var len = $.length;
        if (len == 1) {
            return '\\w';
        }
        return '\\w{' + len + '}'
    });

    return new RegExp(pattern);
}
